<script setup>
// 库存分析
import { ref, onMounted } from 'vue'

const chartOption = ref({
	legend: {
		padding: [30, 0, 10, 100],
		right: '8%',
		orient: 'horizontal',
		type: 'scroll',
		textStyle: { color: '#fff' },
		itemGap: 20,
		pageIconColor: '#fff',
		pageTextStyle: {
			color: '#fff',
		},
	},
	backgroundColor: 'transparent',
	tooltip: {
		formatter: function (param) {
			return `<span style="display:inline-block;margin-right:5px;width:10px;height:10px;border-radius:50%;background:${param.color}"></span>${param.data[2]}<br/>
        统计日期: ${param.data[3]}<br/>
        库存水平: ${param.data[0]}<br/>
        库存周转率: ${param.data[1]}%`
		},
	},
	grid: {
		left: '6%',
		right: '14%',
		bottom: '12%',
		containLabel: true,
	},
	xAxis: {
		scale: true,
		name: '库存水平',
		splitNumber: 3,
	},
	yAxis: {
		scale: true,
		name: '库存周转率',
		splitNumber: 2,
	},
	series: [
		{
			type: 'scatter',
			data: [],
			emphasis: {
				itemStyle: {
					shadowBlur: 10,
					shadowOffsetX: 0,
					shadowColor: 'rgba(0, 0, 0, 0.5)',
				},
			},
		},
	],
})

const fetchInventoryData = async () => {
	try {
		const response = await fetch('http://localhost/api/ads-inventory')
		const apiData = await response.json()

		// 按品牌分组数据
		const brandGroups = apiData.reduce((acc, item) => {
			if (!acc[item.brand]) {
				acc[item.brand] = []
			}
			acc[item.brand].push(item)
			return acc
		}, {})

		// 生成系列配置
		chartOption.value.series = Object.entries(brandGroups)
			.sort((a, b) => a[0].localeCompare(b[0])) // 品牌名称排序
			.map(([brand, items], index) => ({
				name: brand,
				type: 'scatter',
				data: items.map(i => [i.avgInventoryLevel, i.inventoryTurnoverRate, brand, i.statisticDate]),
				itemStyle: {
					color: ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'][index], // 按品牌顺序固定颜色
				},
				emphasis: {
					itemStyle: {
						shadowBlur: 10,
						shadowOffsetX: 0,
						shadowColor: 'rgba(0, 0, 0, 0.5)',
					},
				},
			}))
	} catch (error) {
		console.error('获取库存数据失败:', error)
	}
}

onMounted(() => {
	fetchInventoryData()
})
</script>

<template>
	<v-chart theme="chalk" :option="chartOption" />
</template>

<style scoped></style>
